package com.example.consumer;

import com.example.util.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ReceiverWithFanoutExchange {

    // 定义交换机的名称
    private static final String EXCHANGE_NAME = "test-fanout-exchange";

    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectionUtils.openConnection(null);
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue();
        // 将队列和交换机进行绑定
        // 在对于fanout交换机而言，routingKey会被忽略，所以只需传空字符串
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        String queue2Name = channel.queueDeclare().getQueue();
        channel.queueBind(queue2Name, EXCHANGE_NAME, "");

        String queue3Name = "test-queue-testing-fanout";
        channel.queueDeclare(queue3Name, false, false, false, null);
        channel.queueBind(queue3Name, EXCHANGE_NAME, "");

        channel.basicConsume(
                queueName,
                true,
                (consumerTag, message) -> System.out.println("从队列" + queueName + "收到消息：" + new String(message.getBody())),
                consumerTag -> {
                });

        channel.basicConsume(
                queue2Name,
                true,
                (consumerTag, message) -> System.out.println("从队列" + queue2Name + "收到消息：" + new String(message.getBody())),
                consumerTag -> {
                });
    }
}
